#pragma once
#include <iostream>
#include <string>
#include<cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include <cerrno>
#include <cstdlib>
#include <arpa/inet.h>
#include <strings.h>
#include <netinet/in.h>
#include <cstdlib>
#include <unistd.h>
#include"InetAddr.hpp"
#include<functional>
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};
const static int defaultfd = -1;
using func_t=std::function<void(int sockfd,const std::string&,const InetAddr&)>;
class Udpserver
{
public:
    Udpserver( uint16_t port,func_t func) : _sockfd(defaultfd), _port(port),  _isrunning(0),_func(func)
    {
    }

    void InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error,%s,%d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success,socket:%d\n", _sockfd);
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;;
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error,%s,%d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "socketbind success\n");
    }
    void Start()
    {
        _isrunning = true;
        while (1)
        {
            char  message[1024];
            struct sockaddr_in peer;
            socklen_t len =sizeof(peer);
           ssize_t n=recvfrom(_sockfd, message,sizeof(message)-1,0,(struct sockaddr*)&peer,&len);
           if(n>0)
           {
            message[n]=0;
            InetAddr addr(peer);
            LOG(DEBUG,"get message from:[%s:%d]:%s\n",addr.IP().c_str(),addr.Port(),message);
            _func(_sockfd,message,addr);
          // bool ok;
           // std::string response=_func(request,ok);
            //(void)(ok);
            
            //sendto(_sockfd,message,sizeof(message)-1,0,(struct sockaddr*)&peer,len);
           }
        }
    }
    ~Udpserver()
    {
    }

private:
    int _sockfd;
    //std::string _ip;
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};